<template>
  <!-- 流程详细页面--流程意见 -->
  <div v-if="isHasIdea > 0 || flowType == 'default'" style="height: 300px" class="idea-table-box">
    <div class="idea-table table-wrapper">
      <AvicTable
        :row-key="(record) => record.key"
        :bordered="true"
        :columns="columns"
        :loading="loading"
        :data-source="list"
        :show-toolbar="false"
        :show-table-setting="false"
        :page-parameter="queryParam.pageParameter"
        :auto-height="true"
        :total="totalPage"
        :scroll="{ y: 100 }"
        @change="handleTableChange"
      >
        <template #bodyCell="{ column, text, record, index }">
          <template v-if="column.dataIndex === 'signphoto' && record.showSign === '1'">
            <img v-if="record.showSign === '1'" :src="record.signphoto" alt="电子签名" class="user-avatar" />
          </template>
        </template>
      </AvicTable>
    </div>
    <!-- <a-empty v-else :image="simpleImage" /> -->
  </div>
</template>

<script setup lang="ts">
// import { Empty } from 'ant-design-vue';
import { getToken } from '@/utils/common-util';
import { getFlowOpinions } from '@/api/avic/bpm/BpmOpinionApi';
const { proxy } = getCurrentInstance();

const props = defineProps({
  /** 流程实例 */
  bpmInstanceObject: { type: Object, default: null }
});
const columns = ref([
  {
    title: '意见名称',
    dataIndex: 'title',
    width: 140,
    align: 'center',
    autoHeight: true,
    customRender: ({ record }) => {
      const obj = {
        props: {} as any
      };
      if (record.index === 0) {
        obj.props.rowSpan = record.rowSpan;
      } else {
        obj.props.rowSpan = 0;
      }
      return obj;
    }
  },
  {
    title: '电子签名',
    dataIndex: 'signphoto',
    width: 180,
    visible: false,
    ellipsis: true,
    align: 'left'
  },
  {
    title: '意见内容',
    dataIndex: 'ideaContent',
    visible: true,
    // ellipsis: true,
    autoHeight: true,
    align: 'left'
  }

  // {
  //   title: '用户',
  //   dataIndex: 'user',
  //   visible: true,
  //   ellipsis: true,
  //   align: 'left'
  // },
  // {
  //   title: '时间',
  //   dataIndex: 'time',
  //   visible: true,
  //   ellipsis: true,
  //   align: 'left'
  // },

  // {
  //   title: '部门',
  //   dataIndex: 'dept',
  //   ellipsis: true,
  //   visible: true,
  //   align: 'left'
  // },
  // {
  //   title: '日期',
  //   dataIndex: 'day',
  //   ellipsis: true,
  //   visible: true,
  //   align: 'left'
  // },
  // {
  //   title: '表态',
  //   dataIndex: 'compel',
  //   visible: true,
  //   ellipsis: true,
  //   align: 'left'
  // }
]);
const token = getToken();
const queryParam = reactive({
  // 请求表格数据参数
  pageParameter: {
    page: 1, // 页数
    rows: 20 // 每页条数
  },
  searchParams: {},
  keyWord: ref(''), // 快速查询数据
  sidx: null, // 排序字段
  sord: null // 排序方式: desc降序 asc升序
});
const list = ref([]);
const totalPage = ref(0);
const loading = ref(false); // 表格loading状态
const isHasIdea = ref(false);
const flowType = window.$config?.flow?.flowDetailStyle || 'default';
// const simpleImage = ref(Empty.PRESENTED_IMAGE_SIMPLE);
onMounted(() => {
  getList();
});

/** 查询数据 */
function getList() {
  loading.value = true;
  getFlowOpinions({ entryId: props.bpmInstanceObject.bpmModel.entryId })
    .then((res) => {
      isHasIdea.value = res.data.ideaCode.length > 0;
      const dataList = res.data.result;
      dataList?.forEach((item) => {
        item?.forEach((tim) => {
          tim.index = item.indexOf(tim);
          tim.rowSpan = item.indexOf(tim) === 0 ? item.length : 0;
          tim.ideaContent = tim.displayStyle
            .split(',')
            .map((code) => tim[code])
            .toString();
          if (tim.showSign === '1') {
            columns.value.forEach((e) => {
              if (e.dataIndex === 'signphoto') {
                e.visible = true;
                getTokenAvatar(
                  `${proxy.$settings.axiosRequestConfig.baseURL}/appsys/user/user/sign/get/${tim.userId}`,
                  'signphotoImageUrl',
                  tim
                );
              }
            });
          }

          // columns.value.forEach((e) => {
          //   if (!tim.displayStyle.includes(e.dataIndex)) {
          //     e.visible = false;
          //   }
          //   if (e.dataIndex === 'title') {
          //     e.visible = true;
          //   }
          //   if (tim.showSign === '1' && e.dataIndex === 'signphoto') {
          //     e.visible = true;
          //     getTokenAvatar(`/api/appsys/user/user/sign/get/${tim.userId}`, 'signphotoImageUrl', tim);
          //   }
          // });
          list.value.push(tim);
          totalPage.value = list.value.length;
        });
      });
      list.value.forEach((item) => (item.key = proxy.$uuid()));
      list.value = [...list.value];
      loading.value = false;
    })
    .catch(() => {
      list.value = [];
      loading.value = false;
    });
}
/**
 * 表头排序
 * @param pagination 分页数据
 * @param sorter 排序方式
 */
function handleTableChange(pagination) {
  queryParam.pageParameter.page = pagination.current;
  queryParam.pageParameter.rows = pagination.pageSize;
  // getList();
}
// 获取用户头像
function getTokenAvatar(url: string, variableName: string, record) {
  const xmlhttp = new XMLHttpRequest();
  xmlhttp.open('GET', url, true);
  xmlhttp.responseType = 'arraybuffer';
  xmlhttp.setRequestHeader('X-Access-Token', token);

  // if (this.$getMicroToken()) {
  //   xmlhttp.setRequestHeader(
  //     'x-kong-api-key',
  //     'bearer ' + this.$getMicroToken()
  //   );
  // }
  xmlhttp.onload = () => {
    if (xmlhttp.status === 200) {
      if (xmlhttp.response.byteLength) {
        const buffer = new Uint8Array(xmlhttp.response).reduce((data, byte) => data + String.fromCharCode(byte), '');
        if (variableName === 'signphotoImageUrl') {
          record.signphoto = `data:image/png;base64,${btoa(buffer)}`;
        }
      }
    }
  };
  xmlhttp.send();
}
</script>
<style lang="less" scoped>
.idea-table {
  padding: 0;
}
.user-avatar {
  width: 100px;
  height: 50px;
  border-radius: 8px;
}
</style>
